<template>
  <div class="marketing-edit">
    <div class="page-header">
      <div class="header-left">
        <el-button @click="router.back()">
          <i class="fas fa-arrow-left"></i> 返回
        </el-button>
        <h2>{{ isEdit ? "编辑活动" : "新增活动" }}</h2>
      </div>
      <div class="header-right">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </div>
    </div>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="marketing-form"
    >
      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <span>活动信息</span>
          </div>
        </template>

        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入活动名称" />
        </el-form-item>

        <el-form-item label="活动类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择活动类型">
            <el-option label="限时折扣" value="flash" />
            <el-option label="满减优惠" value="fullReduction" />
            <el-option label="套餐优惠" value="package" />
            <el-option label="秒杀活动" value="seckill" />
          </el-select>
        </el-form-item>

        <el-form-item label="活动海报" prop="poster">
          <el-upload
            class="poster-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handlePosterSuccess"
            :before-upload="beforePosterUpload"
          >
            <img v-if="form.poster" :src="form.poster" class="poster-image" />
            <i v-else class="fas fa-plus upload-icon"></i>
          </el-upload>
          <div class="upload-tip">建议尺寸：800x400px，支持jpg、png格式</div>
        </el-form-item>

        <el-form-item label="活动时间" prop="timeRange">
          <el-date-picker
            v-model="form.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>

        <el-form-item label="参与商品" prop="products">
          <el-select
            v-model="form.products"
            multiple
            filterable
            remote
            :remote-method="handleProductSearch"
            placeholder="请选择参与活动的商品"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <div class="product-option">
                <el-image :src="item.image" class="product-image" />
                <div class="product-info">
                  <div class="product-name">{{ item.name }}</div>
                  <div class="product-price">¥{{ item.price }}</div>
                </div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="优惠方式"
          prop="discountType"
          v-if="form.type !== 'package'"
        >
          <el-radio-group v-model="form.discountType">
            <el-radio label="percent">折扣</el-radio>
            <el-radio label="amount">直减</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          :label="form.discountType === 'percent' ? '折扣比例' : '优惠金额'"
          prop="discountValue"
          v-if="form.type !== 'package'"
        >
          <el-input-number
            v-model="form.discountValue"
            :min="form.discountType === 'percent' ? 0 : 0.01"
            :max="form.discountType === 'percent' ? 100 : 99999"
            :precision="form.discountType === 'percent' ? 0 : 2"
            :step="form.discountType === 'percent' ? 1 : 10"
          />
          <span class="form-tip">{{
            form.discountType === "percent" ? "%" : "元"
          }}</span>
        </el-form-item>

        <el-form-item label="活动说明" prop="description">
          <el-input
            type="textarea"
            v-model="form.description"
            :rows="4"
            placeholder="请输入活动说明"
          />
        </el-form-item>

        <el-form-item label="活动规则" prop="rules">
          <el-input
            type="textarea"
            v-model="form.rules"
            :rows="4"
            placeholder="请输入活动规则"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="draft">草稿</el-radio>
            <el-radio label="published">发布</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-card>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";

const route = useRoute();
const router = useRouter();
const formRef = ref(null);

const isEdit = computed(() => !!route.params.id);

// 表单数据
const form = reactive({
  name: "",
  type: "",
  description: "",
  status: "draft",
  poster: "",
  timeRange: [],
  products: [],
  discountType: "percent",
  discountValue: 0,
  rules: "",
});

// 商品选项
const productOptions = ref([
  {
    id: 1,
    name: "示例商品1",
    image: "https://example.com/product1.jpg",
    price: 99,
  },
]);

// 表单验证规则
const rules = {
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择类型", trigger: "change" }],
  timeRange: [{ required: true, message: "请选择活动时间", trigger: "change" }],
  products: [{ required: true, message: "请选择参与商品", trigger: "change" }],
};

// 获取营销活动信息
const getMarketingInfo = async (type, id) => {
  try {
    // TODO: 调用获取详情API
    const response = await getMarketing(type, id);
    Object.assign(form, response.data);
  } catch (error) {
    ElMessage.error("获取信息失败");
  }
};

// 海报上传
const handlePosterSuccess = (res, file) => {
  form.poster = URL.createObjectURL(file.raw);
};

const beforePosterUpload = (file) => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error("上传海报只能是 JPG 或 PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传海报大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 商品搜索
const handleProductSearch = async (query) => {
  if (query) {
    // TODO: 调用商品搜索API
    const response = await searchProducts(query);
    productOptions.value = response.data;
  } else {
    productOptions.value = [];
  }
};

// 取消
const handleCancel = () => {
  router.back();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate((valid, fields) => {
    if (valid) {
      // TODO: 调用保存API
      ElMessage.success(isEdit.value ? "更新成功" : "添加成功");
      router.back();
    }
  });
};

onMounted(() => {
  if (route.params.id) {
    getMarketingInfo(route.params.type, route.params.id);
  }
});
</script>

<style lang="less" scoped>
.marketing-edit {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;

    h2 {
      margin: 0;
      font-size: 24px;
    }
  }

  .header-right {
    display: flex;
    gap: 12px;
  }
}

.marketing-form {
  max-width: 800px;
  margin: 0 auto;
}

.form-card {
  margin-bottom: 20px;
}

.poster-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }

  .poster-image {
    width: 400px;
    height: 200px;
    display: block;
    object-fit: cover;
  }
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  width: 400px;
  height: 200px;
  text-align: center;
  line-height: 200px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-left: 12px;
}

.product-option {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px;
}

.product-image {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
}

.product-info {
  flex: 1;

  .product-name {
    font-size: 14px;
    margin-bottom: 4px;
  }

  .product-price {
    font-size: 12px;
    color: #f56c6c;
  }
}
</style>
